package main


import (
    "fmt"
    "io/ioutil"
    "os"
    "time"
)
/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L./ -lmp3
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "libmad_play.h"

unsigned char* win_read( int *len, const char* path) {
    
    setvbuf(stdout, NULL, _IONBF, 0);      
    FILE *pFile = fopen(path, "rb");
    int file_len, ret;
    unsigned char *buf;
    //unsigned char buf[1024*1024*4];

    if ( pFile == NULL ) {
        return 0;
    }else 
        printf("mp3path open ok\n");

    fseek(pFile, 0, SEEK_END);
    file_len = ftell( pFile );
    rewind(pFile);
    buf = malloc(file_len);

    printf("file_len is %d\n", file_len);
    if(buf) {
        ret = fread(buf, 1, (size_t)file_len, pFile);
    }
    printf("ret is %d\n", ret);
    fclose(pFile);

    *len = ret;
    return buf;
}



static void test(unsigned char* buf, unsigned int len) 
{
    unsigned int wlen;
    while(len > 0) {
        if(len > 1024) {
            wlen = 1024;
        }else {
            wlen = len;
        }
        while(mp3_buf_depth() >= 60) {
            usleep(10*1000);
        }
        mp3_buf_write(buf, wlen);
        len-=wlen;
        buf+=wlen;
    }
    while(mp3_buf_depth() != 0) {
        usleep(100*1000);
    }
}

int hi()
{
    char *mp3path = "300.mp3";
    void *fdm;
    int len;

    fdm = win_read(&len, mp3path);
   
    while(1) {
        test(fdm, len);
    }
    return 0;
}
*/
import "C" //这里可看作封装的伪包C, 这条语句要紧挨着上面的注释块，不可在它俩之间间隔空行！


func read3(path string) []byte {
    fi, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer fi.Close()
    fd, err := ioutil.ReadAll(fi)
    if err != nil {
        fmt.Println("read to fd fail", err)
    }

    return fd
}


func main() {
	a := read3("test.mp3")
	
	C.libmad_init()
	C.libmad_media_start(2,48000)
	for ture {
		for C.mp3_buf_depth() > 60 {
			time.Sleep(1*time.Millisecond)
		}
		C.mp3_buf_write()


	}


	
    C.hi()
	C.libmad_media_stop_sync();
    fmt.Println("Hi, vim-go")
}